package com.example.filter;

import com.example.util.JwtUtil;
import com.example.util.Result;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //获取访问路径
        String requestURI = httpServletRequest.getRequestURI();
        System.out.println(requestURI);
        //判定访问路径，如果为login就直接放行
        if (requestURI.equals("/login") || isSwaggerPath(requestURI)) {
            doFilter(httpServletRequest, httpServletResponse, filterChain);
            return;
        }
//获取请求头
        String jwtToken = httpServletRequest.getHeader("Authorization");
//判定请求头是否为空
        if (StringUtils.isEmpty(jwtToken)){
            Result result=Result.builder()
                    .flag(false)
                    .msg("header为空")
                    .build();
            printToken(httpServletRequest, httpServletResponse,result);
            return;
        }
//获取token
        //String jwtToken = authorization.replace("bearer ", "");
        //判定token是否为空
        if (StringUtils.containsWhitespace(jwtToken)){
            Result result=Result.builder()
                    .flag(false)
                    .msg("jwt为空")
                    .build();
            printToken(httpServletRequest, httpServletResponse,result);
            return;
        }
//判定token是否合法
        boolean verifyToken = jwtUtil.verifyToken(jwtToken);
        if (!verifyToken){
            Result result=Result.builder()
                    .flag(false)
                    .msg("jwt非法")
                    .build();
            printToken(httpServletRequest, httpServletResponse,result);
            return;
        }

        String s = stringRedisTemplate.opsForValue().get("logintoken" + jwtToken);
        if (StringUtils.isEmpty(s)){
            Result result=Result.builder()
                    .flag(false)
                    .msg("已退出")
                    .build();
            printToken(httpServletRequest, httpServletResponse,result);
            return;
        }

        //获取用户信息
        String username = jwtUtil.verify(jwtToken, "username");
        //获取权限
        List<String> userAuth = jwtUtil.getUserAuth(jwtToken);
        //权限转化
        List<SimpleGrantedAuthority> authorities=userAuth.stream().map((SimpleGrantedAuthority::new)).collect(Collectors.toList());
        //生成security的token
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, null, authorities);
        //将security的token放入到sercurity的上下文中
        SecurityContextHolder.getContext().setAuthentication(token);
        //放行请求
        doFilter(httpServletRequest, httpServletResponse, filterChain);



    }
    private boolean isSwaggerPath(String requestURI) {
        return requestURI.startsWith("/swagger") ||
                requestURI.equals("/v2/api-docs") ||
                requestURI.startsWith("/swagger-resources") ||
                requestURI.startsWith("/webjars");
    }
    public void printToken(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Result build) throws IOException {
        String s = objectMapper.writeValueAsString(build);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json,charset=UTF-8");
        PrintWriter writer = httpServletResponse.getWriter();
        writer.print(s);
        writer.flush();

    }
}
